<template>
	<view>
		<!-- 广告 -->
		<view>
			<ad adpid="1206517737" type="banner" @load="adOnload" @close="adOnclose" @error="adOnerror"></ad>
		</view>
		<!-- <view> -->
			<!-- <ad-rewarded-video ref="adRewardedVideo" adpid="1851307261" :preload="false" :loadnext="false"
				:disabled="true" v-slot:default="{loading, error}" @load="onadload" @close="onadclose"
				@error="onaderror">
				<view class="ad-error" v-if="error">{{error}}</view>
			</ad-rewarded-video> -->
			<!-- :disabled="isLoading" :loading="isLoading"  -->
			<!-- <button type="primary" @click="showAd">显示广告</button> -->
		<!-- </view> -->
		<view class="content">
			<!-- <uni-list class="list">
			<uni-list-item title="创建wifi" clickable @click="toCreatePage" />
			<uni-list-chat :avatar-circle="true" title="头像" :avatar="viviewew" note="您收到一条新的消息" time="2020-02-02 20:20" ></uni-list-chat>
		</uni-list> -->
			<view class="item item2" @click="toCreatePage">
				<view class="left">
					<image src="/static/WIFI.png" mode="widthFix"
						style="width:120rpx;height: 100%;background-color: #007aff"></image>
				</view>
				<view class="left1">
					<view>
						创建WiFi
					</view>
					<view class="bottom">
						快速查看并管理您的WiFi码
					</view>
				</view>
				<view class="right">
					<uni-icons type="arrow-right" size="28" color="#999999"></uni-icons>
				</view>
			</view>
			<view class="item item2" @click="toMngWifi">
				<view class="left">
					<cloud-image v-if="hasLogin&&userInfo.data.avatar_file" :src="userInfo.data.avatar_file.url"
						width="120rpx" height="100%">
					</cloud-image>
					<uni-icons v-else custom-prefix="iconfont" type="icon-anonymous" size="60"></uni-icons>
				</view>
				<view class="left1">
					<view v-if="hasLogin">
						{{ userInfo.data.nickname}}
					</view>
					<view class="bottom">
						快速查看并管理您的WiFi码
					</view>
				</view>
				<view class="right">
					<uni-icons type="arrow-right" size="28" color="#999999"></uni-icons>
				</view>
			</view>
		</view>
		<ad adpid="1733174380" @load="adOnload" @error="adOnerror"></ad>
	</view>
</template>

<script>
	import {
		onLoad,
		// onReady
	} from '@dcloudio/uni-app';
	const db = uniCloud.database();
	const usersTable = db.collection('uni-id-users')
	// const userRoleTable = db.collection('uni-id-roles')
	const uniIdCo = uniCloud.importObject("uni-id-co")


	import {
		ref,
		reactive
	} from 'vue';

	export default {
		setup() {
			// const data  = uni.getAccountInfoSync()
			// console.log("data",data)
			const userProfileRef = ref();
			const hasLogin = ref(false);
			const hasUserNotNickName = ref(false);
			const userInfo = reactive({
				data: {}
			})
			// 广告相关
			const isLoading = ref(false)
			const adRewardedVideo = ref(null)
			// 广告相关结束


			const toCreatePage = async () => {
				// console.log("hasLogin", hasLogin.value)
				if (hasLogin.value) {
					uni.navigateTo({
						url: "/subpkgWifi/createWifi/createWifi"
					})
				} else {
					// getUserInfo(true)
					loginByWeixin()
				}

			}

			const toMngWifi = () => {
				// console.log("hasLogin", hasLogin.value)
				if (hasLogin.value) {
					uni.navigateTo({
						url: "/subpkgWifi/wifiList"
					})
				} else {
					// getUserInfo(true)
					loginByWeixin()
				}
			}

			// onReady(() => {
			// 	console.log("onReady")
			// 	// isLoading.value = true
			// 	adRewardedVideo.value.load();
			// })

			onLoad(() => {
				// isLoading.value = false
				// console.log("isLoading",isLoading.value)
				uni.showLoading({
					mask: true
				});
				// 1.获取用户信息
				getUserInfo(true)

				uni.$on('reloadIndex', () => {
					getUserInfo(true)
				});
				// loginByWeixin()
			})

			// const showAd = () => {
			// 	console.log("显示激励视频广告")
			// 	console.log("sLoading.value",isLoading.value)
			// 	if (isLoading.value) {
			// 		return
			// 	}
			// 	adRewardedVideo.value.show();
			// }

			// const onadload = (e) => {
			// 	console.log('激励广告数据加载成功');
			// }

			// const onadclose = (e) => {
			// 	console.log("激励视频-用户点击了【关闭广告】按钮")
			// 	const detail = e.detail
			// 	// 用户点击了【关闭广告】按钮
			// 	if (detail && detail.isEnded) {
			// 		// 正常播放结束
			// 		console.log("onadclose " + detail.isEnded);
			// 	} else {
			// 		// 播放中途退出
			// 		console.log("onadclose " + detail.isEnded);
			// 	}
			// };
			// const onaderror = (e) => {
			// 	// 广告加载失败
			// 	console.log("激励视频加载失败: ", e.detail);
			// }

			// 先去获取用户授权
			// 2.获取用户信息没的话就去登录
			const loginByWeixin = async () => {
				// console.log("login")
				uni.showLoading({
					mask: true,
					title: '用户登录中'
				});
				// uni.navigateTo({
				// 	url: "pages/login/pages/login/login-withoutpwd?type=weixin"
				// })
				let res = await new Promise((callBack) => {
					uni.getUserProfile({
						desc: "用于设置账户昵称和头像",
						complete: (e) => {
							// console.log("getUserProfile:", e);
							callBack(e)
						}
					})
				})
				// console.log("userInfo", res.userInfo);
				if (res.errMsg != "getUserProfile:ok") {
					uni.showToast({
						title: '用户取消授权',
						icon: 'none'
					});
					uni.hideLoading()
					return
				}


				const type = "weixin"
				// 先只支持微信登录
				uni.login({
					"provider": type,
					"onlyAuthorize": true,
					success: async e => {
						// console.log("e微信登录完成", e);
						// 先去调用登录获取小程序的鉴权信息
						login({
							code: e.code
						}, type, res)
					},
					fail: async (err) => {
						// console.log("微信登录err", err);
						uni.hideLoading()
					}
				})
			}
			const login = (params, type, userInfoRes) => { //联网验证登录
				// console.log({
				// 	params,
				// 	type
				// });
				//toLowerCase
				let action = 'loginBy' + type.trim().toLowerCase().replace(type[0], type[0].toUpperCase())
				const uniIdCo = uniCloud.importObject("uni-id-co", {
					customUI: true
				})
				uniIdCo[action](params).then(result => {
						// console.log("调用云对象登录login-result", result);
						// #ifdef MP-WEIXIN
						//如果是微信小程序端的微信登录，且为首次登录，就弹出获取微信昵称+头像用于绑定资料
						if (type == 'weixin' && result.type == "register") {
							// console.log("现在是注册")
							// loginSuccess({
							// 	...result,
							// 	showToast: false,
							// 	autoBack: false
							// })
							// return
							// userProfileRef.value.open(result.uid)
							updateUserInfo(result.uid, userInfoRes)
						} else {
							// console.log("现在不是注册，直接登录")
							uni.showToast({
								title: '登录成功',
								icon: 'none'
							});
							if (hasUserNotNickName.value) {
								// 已经有用户信息但是没昵称和头像
								updateUserInfo(result.uid, userInfoRes)
							} else {
								// 啥都有了直接获取信息就可以
								getUserInfo()
							}

						}
						// #endif
						// loginSuccess(result)

						// uni.hideToast();
					})
					.catch(e => {
						console.log(e);
						uni.showModal({
							content: e.message,
							confirmText: "知道了",
							showCancel: false
						});
					})
					.finally(e => {
						uni.hideLoading()
					})
			}

			const updateUserInfo = async (userId, userInfoRes) => {
				let res = userInfoRes
				// uni.showLoading();
				// let res = await new Promise((callBack) => {
				// 	uni.getUserProfile({
				// 		desc: "用于设置账户昵称和头像",
				// 		complete: (e) => {
				// 			console.log("getUserProfile:", e);
				// 			callBack(e)
				// 		}
				// 	})
				// })
				// // console.log("userInfo", res.userInfo);
				// if(res.errMsg != "getUserProfile:ok"){
				// 	uni.showToast({
				// 		title: '用户取消授权',
				// 		icon: 'none'
				// 	});
				// 	return
				// }
				// console.log("注册用户信息")
				let {
					avatarUrl,
					nickName
				} = res.userInfo, cloudPath = userId + '/' + Date.now() + 'avatarUrl.jpg';
				// console.log("注册用户信息-nickName",nickName)
				// console.log("注册用户信息-avatarUrl",avatarUrl)
				let tempFilePath = await new Promise((callBack) => {
					uni.downloadFile({
						url: avatarUrl,
						success: (res) => {
							if (res.statusCode === 200) {
								// console.log('下载成功');
								callBack(res.tempFilePath)
							}
							callBack()
						},
						fail: (err) => {
							console.error(err)
						},
						complete: (e) => {
							// console.log("downloadFile",e);
						}
					});
				})
				// console.log(tempFilePath);
				const result = await uniCloud.uploadFile({
					filePath: tempFilePath,
					cloudPath,
					fileType: 'image'
				});
				// console.log("上传成功",{result});
				let userInfo = {
					"nickname": nickName,
					"avatar_file": {
						name: cloudPath,
						extname: "jpg",
						url: result.fileID
					},
					// 如果那个人是连接wifi的则赋予消费者角色
					"role": ["provider"]
				}
				doUpdate(userInfo)
			}
			const doUpdate = (data) => {
				// console.log('dododo',data);
				// 使用 clientDB 提交数据
				usersTable.where('_id==$env.uid').update(data).then((res) => {
					uni.showToast({
						title: '登录成功',
						icon: 'none'
					});
					// console.log("注册完成后更新nicknaem和role成功")
					getUserInfo()
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}

			// 是否在onload里获取的
			const getUserInfo = (flag) => {
				uni.showLoading({
					mask: true
				});
				const user = usersTable.where("'_id' == $cloudEnv_uid").get();
				// console.log(user)
				// 感觉不需要获取角色啊，我为啥要获取角色，有点神奇
				// db.collection(user, 'uni-id-roles').field('mobile,nickname,avatar_file,role').get()
				user.then(res => {
					// console.log("getUserInfo", {
					// 	res
					// });
					const userData = res.result.data[0] || {}
					// console.log("userData", userData)
					if (userData.nickname) {
						userInfo.data = userData
						// console.log('this.userInfo', userInfo.data);
						hasLogin.value = true
						uni.setStorageSync("userInfo", userData)
					} else {
						// console.log("就说明有用户信息，但是用户没头像和昵称,这时候可以获取头像和昵称然后更新一下")
						hasLogin.value = false
						hasUserNotNickName.value = true
						// 那么就要先注册登录
						// if (flag) {
						// 	loginByWeixin()
						// }
					}
				}).catch(e => {
					userInfo.data = {}
					uni.setStorageSync("userInfo", null)
					hasLogin.value = false
					// store.commit("logout")
					// console.log("报错了", e.message, e.errCode);
					// if (flag) {
					// 	loginByWeixin()
					// }

				}).finally(e => {
					// console.log(e);
					uni.hideLoading()
				})
			}

			// 以下广告相关
			const adOnload = (EventHandle) => {
				// console.log("banner广告加载成功", EventHandle)
			}
			const adOnclose = (EventHandle) => {
				// console.log("banner广告关闭", EventHandle)
			}

			const adOnerror = (EventHandle) => {
				// console.log("banner广告错误", EventHandle)
			}
			return {
				toCreatePage,
				getUserInfo,
				hasLogin,
				userProfileRef,
				userInfo,
				toMngWifi,
				adOnload,
				adOnclose,
				adOnerror,
				// isLoading,
				// adRewardedVideo,
				// showAd,
				// onaderror,
				// onadload,
				// onadclose
			}
		}
	}
</script>

<style lang="scss">
	$itemWidth: 60px;

	.item {
		height: $itemWidth;
		padding: 16px 8px;
		background-color: #ffffff;
		margin: 32rpx 16rpx;
		border-radius: 10rpx;
	}

	.item2 {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		justify-content: space-between;

		.left {
			height: 100%;
		}

		.left1 {
			flex: 1;
			margin-left: 32rpx;
			font-size: 46rpx;

			.bottom {
				color: #999;
				font-size: 32rpx;
				margin-top: 5px;
			}
		}

		.right {
			line-height: $itemWidth;

		}
	}
</style>
